package org.dey.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Select;
import org.dey.entity.Result;
import org.dey.mapper.MenuMapper;
import org.dey.mapper.RoleMapper;
import org.dey.pojo.Menu;
import org.dey.pojo.Role;
import org.dey.pojo.User;
import org.dey.service.MenuService;
import org.dey.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

/**
 * @author deyran
 * @date 2022/3/22 21:35
 * @classname
 * @see
 */
@Service
@Transactional
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    MenuMapper menuMapper;

    @Autowired
    RoleService roleService;


    /**
     * SELECT * FROM t_menu WHERE id IN
     * (SELECT menu_id FROM t_role_menu WHERE role_id IN
     * (SELECT role_id FROM t_user_role WHERE t_user_role.user_id IN
     * ( SELECT id FROM t_user WHERE username = 'xiaoming')));
     *
     * @param username
     * @return
     */
    @Override
    public List<Menu> MENU_ROLE_LIST(String username) {
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        List<Role> role = roleService.getRole(username);
        String str = "0";
        if (role.size() != 0) {
            str = "";
        }
        for (int i = 0; i < role.size(); i++) {
            str += role.get(i).getId() + ",";
            if (role.size() - 1 == i) {
                str += role.get(i).getId();
            }
        }
        wrapper.eq("level",1);
        wrapper.inSql("id","SELECT menu_id FROM t_role_menu WHERE role_id IN ("+str+")");
        List<Menu> list = this.list(wrapper);
        for (Menu menu : list) {
            QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parentMenuId", menu.getId());
            menu.setChildren(this.list(queryWrapper));
            menu.setRoles(new HashSet<>(role));
        }
        return list;
    }
}
